package service

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
)

type RequestBody struct {
	MerchNo          string `json:"merch_no"`
	TermNo           string `json:"term_no"`
	OutTradeNo       string `json:"out_trade_no"`
	PaymentValidTime string `json:"payment_valid_time"`
	Description      string `json:"description"`
	Attach           string `json:"attach"`
	ProductName      string `json:"product_name"`
	TotalAmount      int    `json:"total_amount"`
	Remark           string `json:"remark"`
	NotifyURL        string `json:"notify_url"`
	EnvVersion       string `json:"env_version"`
	MerchAppid       string `json:"merch_appid"`
	ReturnURL        string `json:"return_url"`
}

type ResponseBody struct {
	CashierURL string `json:"cashier_url"`
	JlPayAppid string `json:"jl_pay_appid"`
	GhID       string `json:"gh_id"`
	RetCode    string `json:"ret_code"`
	RetMsg     string `json:"ret_msg"`
}

func AliPayApp() {

}

func PayRequests(url string, requestBody any) (ResponseBody, error) {

	jsonData, err := json.Marshal(requestBody)
	if err != nil {
		fmt.Println("Error marshaling JSON:", err)
		return ResponseBody{}, err
	}

	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
	if err != nil {
		fmt.Println("Error creating request:", err)
		return ResponseBody{}, err
	}

	req.Header.Set("Content-Type", "application/json")

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("Error sending request:", err)
		return ResponseBody{}, err
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("Error reading response:", err)
		return ResponseBody{}, err
	}

	var response ResponseBody
	err = json.Unmarshal(body, &response)
	if err != nil {
		fmt.Println("Error unmarshaling response:", err)
		return ResponseBody{}, err
	}

	fmt.Println("Response:")
	fmt.Printf("CashierURL: %s\n", response.CashierURL)
	fmt.Printf("JlPayAppid: %s\n", response.JlPayAppid)
	fmt.Printf("GhID: %s\n", response.GhID)
	fmt.Printf("RetCode: %s\n", response.RetCode)
	fmt.Printf("RetMsg: %s\n", response.RetMsg)

	// Pretty print the response
	prettyJSON, err := json.MarshalIndent(response, "", "    ")
	if err != nil {
		fmt.Println("Error generating pretty JSON:", err)
		return ResponseBody{}, err
	}
	fmt.Println("\nPretty JSON Response:")
	fmt.Println(string(prettyJSON))
	return response, nil
}
